<?php

namespace app\api\model\cps;


use app\api\model\cps\TbSid;
use app\api\model\ExtendConsume;
use app\api\model\UserConsumeLog;
use app\common\model\User;
use app\shopapi\model\ExtendConsumeShop;
use fast\Auth;
use fast\Http;
use think\Log;

require_once ROOT_PATH.'extend/ali-sdk/TopSdk.php';
require_once ROOT_PATH.'extend/ali-sdk/top/TopClient.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkOptimusTouMaterialIdsGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/domain/MaterialQuery.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkDgMaterialRecommendRequest.php';

require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkDgMaterialOptionalUpgradeRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/domain/Ucrowdrankitems.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkActivityInfoGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkSpreadGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/domain/TbkSpreadRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkTpwdCreateRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkItemInfoUpgradeGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkDgNewuserOrderGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkScPublisherInfoSaveRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkScPublisherInfoGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TbkScInvitecodeGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/TopAuthTokenCreateRequest.php';


//淘宝客接口
class Tbk
{
    protected $appkey = '34761414';

    protected $secret = 'a97062c4188fd11f2330da335b1cc758';

    protected $pid = 'mm_6602163506_3111600128_115744050269';

    protected $adzone_id = '115744050269';

    protected $apikey = 'B128mKCQC6bsOxMB2pTm5GRJi15JWgos';

    //活动列表
    public function material($page,$subject)
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;
        $req = new \TbkOptimusTouMaterialIdsGetRequest;
        $material_query = new \MaterialQuery;
        $material_query->page_no=$page;
        $material_query->subject=$subject;
        $material_query->material_type="1";
        $material_query->page_size="20";
        $req->setMaterialQuery(json_encode($material_query));
        $resp = $c->execute($req);
        return $resp->data;
    }

    //商品列表
    public function goods($page,$material_id)
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $req = new \TbkDgMaterialRecommendRequest;
        $req->setPageSize("20");
        $req->setPageNo($page);
        $req->setMaterialId($material_id);
        $req->setAdzoneId($this->adzone_id);
        $resp = $c->execute($req);

        if (isset($resp->result_list)){
            foreach ($resp->result_list->map_data as $v){
                //$v->publish_info->wawa_commission = round($v->publish_info->commission_amount*0.56,2);
                //dump($v->publish_info->income_rate);
                //dump($v->price_promotion_info->zk_final_price);
                //dump(round($v->publish_info->income_rate*$v->price_promotion_info->zk_final_price/100*0.56,2));
                /*if (isset($v->publish_info->income_info->commission_amount)){
                    $v->publish_info->wawa_commission = round(floatval($v->publish_info->income_info->commission_amount)*0.56,2);
                } else {
                    $v->publish_info->wawa_commission = round(floatval($v->publish_info->income_rate)*floatval($v->price_promotion_info->zk_final_price)/100*0.56,2);
                }*/
                $v->publish_info->wawa_commission = round(floatval($v->publish_info->income_rate)*floatval($v->price_promotion_info->zk_final_price)/100*0.56,2);
            }
            return $resp;
        } else {
            return [];
        }
    }

    //查询商品列表
    public function searchgoods($page,$material_id,$keyword,$sort,$has_coupon)
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $req = new \TbkDgMaterialOptionalUpgradeRequest;
        //$req->setStartDsr("10");
        $req->setPageSize("20");
        $req->setPageNo($page);

        $req->setQ($keyword);
        //$req->setMaterialId(4092);
        $req->setSort($sort);
        $req->setAdzoneId($this->adzone_id);
        if ($has_coupon)$req->setHasCoupon('true');

        $resp = $c->execute($req);
        foreach ($resp->result_list->map_data as $v){
            if (isset($v->publish_info->income_info->commission_amount)){
                $v->publish_info->wawa_commission = round(floatval($v->publish_info->income_info->commission_amount)*0.56,2);
            } else {
                $v->publish_info->wawa_commission = round(floatval($v->publish_info->income_rate)*floatval($v->price_promotion_info->zk_final_price)/100*0.56,2);
            }
            //$v->publish_info->wawa_commission = round($v->publish_info->commission_amount*0.56,2);
            //$v->publish_info->wawa_commission = round($v->publish_info->income_rate*$v->price_promotion_info->zk_final_price/100*0.56,2);
        }
        return $resp;
    }

    //商品详情
    public function goodsdetail($item_id)
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $req = new \TbkItemInfoUpgradeGetRequest;
        $req->setItemId($item_id);
        $req->setRelationId('3114292063');
        $resp = $c->execute($req);
        //dump($resp->results->tbk_item_detail[0]);die;
        $income_rate = $resp->results->tbk_item_detail[0]->publish_info->income_rate;
        $zk_final_price = $resp->results->tbk_item_detail[0]->price_promotion_info->zk_final_price;
        $wawa_commission =  round($income_rate*$zk_final_price*0.56/100,2);
        $resp->results->tbk_item_detail[0]->publish_info->wawa_commission =  $wawa_commission;

        return $resp;
    }

    //转链
    public function privilege($item_id,$user_id)
    {
        $api = "http://api.tbk.dingdanxia.com/tbk/id_privilege";
        //dump($user_id);die;
        $tb_sid_exist = TbSid::where(['use_status'=>1,'user_id'=>$user_id])->field('id,relation_id,pid')
            ->order('createtime asc')->find();
        if ($tb_sid_exist){
            $relation_id = $tb_sid_exist['relation_id'];
            $pid = $tb_sid_exist['pid'];
        } else {
            $tb_sid_info = TbSid::where(['use_status'=>0])->field('id,relation_id,pid')
                ->order('createtime asc')->find();
            $relation_id = $tb_sid_info['relation_id'];
            $pid = $tb_sid_info['pid'];
            $tb_sid = $tb_sid_info['id'];
        }

        $data = [
            'apikey'=>$this->apikey,
            'id'=>$item_id,
            'itemInfo'=>true,
            'shorturl'=>true,
            'tpwd'=>true,
            'relation_id'=>$relation_id,
            'pid'=>$pid,
        ];
        Log::error('转链:privilege');
        Log::error(json_encode($data,320));
        $res = Http::sendRequest($api,$data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            $info =  $result['data'];
            $qh_final_commission =  $info['itemInfo']['qh_final_commission'];
            $wawa_commission =  round($qh_final_commission*0.56,2);
            $info['itemInfo']['wawa_commission'] = $wawa_commission;
            if ($tb_sid_exist){
                TbSid::update(['last_use_time'=>time()],['id'=>$tb_sid_exist['id']]);
            } else {
                TbSid::update(['user_id'=>$user_id,'use_status'=>1,'use_time'=>time()],['id'=>$tb_sid]);
            }

            return $info;
        } else {
            throw new \Exception($result['msg']);
        }
    }

    //url转链
    public function urlprivilege($content)
    {
        $api = "http://api.tbk.dingdanxia.com/tbk/wn_convert";

        $data = [
            'apikey'=>$this->apikey,
            'content'=>$content,
            'itemInfo'=>true,
            'shorturl'=>true,
            'tpwd'=>true,
        ];

        $res = Http::sendRequest($api,$data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            $info =  $result['data'];
            $qh_final_commission =  $info['itemInfo']['qh_final_commission'];
            $wawa_commission =  round($qh_final_commission*0.56,2);
            $info['itemInfo']['wawa_commission'] = $wawa_commission;
            return [
                'code'=>1,
                'data'=>$info
            ];
        } else {
            return [
                'code'=>0,
                'data'=>null,
                'msg'=>$result['msg']
            ];
        }
    }

    //官方活动转链
    public function activityUrl($activity_material_id,$user_id)
    {
        $api = "http://api.tbk.dingdanxia.com/tbk/tc_general_convert";

        $tb_sid_exist = TbSid::where(['use_status'=>1,'user_id'=>$user_id])->field('id,relation_id,pid')
            ->order('createtime asc')->find();
        if ($tb_sid_exist){
            $relation_id = $tb_sid_exist['relation_id'];
            $pid = $tb_sid_exist['pid'];
        } else {
            $tb_sid_info = TbSid::where(['use_status'=>0])->field('id,relation_id,pid')
                ->order('createtime asc')->find();
            $relation_id = $tb_sid_info['relation_id'];
            $pid = $tb_sid_info['pid'];
            $tb_sid = $tb_sid_info['id'];
        }

        $data = [
            'apikey'=>$this->apikey,
            'pid'=>$pid,
            'page_id'=>$activity_material_id,
            'relation_id'=>$relation_id
        ];
        Log::error('官方活动转链:activityUrl');
        Log::error(json_encode($data,320));

        $res = Http::sendRequest($api,$data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            if ($tb_sid_exist){
                TbSid::update(['last_use_time'=>time()],['id'=>$tb_sid_exist['id']]);
            } else {
                TbSid::update(['user_id'=>$user_id,'use_status'=>1,'use_time'=>time()],['id'=>$tb_sid]);
            }
            return $result['data'];
        } else {
            throw new \Exception($result['msg']);
        }
    }
    /*public function activityUrl($activity_material_id,$user_id)
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $req = new \TbkActivityInfoGetRequest;
        $req->setActivityMaterialId($activity_material_id);
        $req->setAdzoneId($this->adzone_id);
        //$req->setSubPid($this->pid);
        $req->setUnionId($user_id);
        $resp = $c->execute($req);
        return $resp;
    }*/

    //长链转短链
    public function changeShortUrl($url)
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $req = new \TbkSpreadGetRequest;
        $requests = new \TbkSpreadRequest;
        $requests->url=$url;

        $req->setRequests(json_encode($requests));
        $resp = $c->execute($req);
        return $resp->results->tbk_spread;
    }

    //淘口令生成
    public function wordCommandCreate($url,$user_id)
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;
        $req = new \TbkTpwdCreateRequest;
        $req->setUrl($url);
        $req->setUserId($user_id);
        $resp = $c->execute($req);
        return $resp;
    }

    //淘宝客-公用-私域用户备案
    public function savepublisher($invitecode)
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;
        $req = new \TbkScPublisherInfoSaveRequest;
        $req->setInviterCode($invitecode);
        $req->setInfoType("1");
        $session = "6101c20073e0953f3d482040270915031ff6bebd2fbf36b3342916414";

        $resp = $c->execute($req,$session);
        return $resp;
    }

    public function getpublisher()
    {
        $api = "http://api.tbk.dingdanxia.com/tbk/publisher_get";

        $data = [
            'apikey'=>$this->apikey,
            'info_type'=>1,
            'relation_app'=>'common',
            'page_no'=>9,
            'page_size'=>1
        ];

        $res = Http::sendRequest($api,$data);

        $result = json_decode($res['msg'],true);

        /*if ($result['code']==200){
            $map_data = $result['data']['inviter_list']['map_data'];
            $root_pid_channel_list = $result['data']['root_pid_channel_list'];

            foreach ($map_data as $k=>$v){

                foreach ($root_pid_channel_list['string'] as $kk=>$vv){
                    $sid_arr=[
                        'sid'=>$v['account_name'],
                        'relation_id'=>$v['relation_id'],
                        'pid'=>$vv,
                        'sid_key'=>$vv.'_'.$v['relation_id']
                    ];
                    $sid_model = new TbSid();
                    $sid_model->save($sid_arr);
                }

            }
        }*/
        //dump(count($map_data));
        return $result['data'];

    }

    //淘宝客-公用-私域用户备案信息查询
    public function oldgetpublisher()
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;
        $req = new \TbkScPublisherInfoGetRequest;
        $req->setInfoType(1);
        $req->setRelationApp("common");
        $req->setPageNo(1);
        $req->setPageSize(100);
        $session = "6101520e64c8bbe264fda26066e111903c196896b2d31e71800230868";
        $resp = $c->execute($req, $session);
        $map_data = $resp->data->inviter_list->map_data;
        $root_pid_channel_list = $resp->data->root_pid_channel_list;

        foreach ($map_data as $k=>$v){
            $sid_arr=[
                'sid'=>$v->account_name,
                'relation_id'=>$v->relation_id
            ];

            $sid_model = new TbSid();
            $sid_model->save($sid_arr);
        }
        return $resp;
    }

    //淘宝客-公用-私域用户邀请码生成
    public function invitecode()
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;
        $req = new \TbkScInvitecodeGetRequest;
        $req->setRelationApp("common");
        $req->setCodeType("1");
        $session = "6100c06c86e1541cc614c504a08deec3430825e043e00721800230868";
        $resp = $c->execute($req, $session);
        return $resp;
    }



    //订单
    public function orderlist()
    {
        $start_time = date('Y-m-d H:i:s',time()-60);
        $end_time = date('Y-m-d H:i:s',time());
        //$start_time = '2024-09-29 10:55:04';
        //$end_time = '2024-09-29 11:30:04';
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;
        $req = new \TbkDgNewuserOrderGetRequest;
        $req->setPageSize("100");
        $req->setPageNo("1");
        $req->setAdzoneId($this->adzone_id);
        $req->setStartTime($start_time);
        $req->setEndTime($end_time);
        $resp = $c->execute($req);

        return $resp;
    }

    //查询未结算的订单
    public function unliquidated()
    {
        $lists = UserConsumeLog::where(['cps_type'=>7,'consume_type'=>2,'is_to_account'=>0,'is_common'=>0])
            ->field('pay_time')->select();

        foreach ($lists as $k=>$v){
            $start = date('Y-m-d H:i:s',$v['pay_time']-1800);
            $end = date('Y-m-d H:i:s',$v['pay_time']);
            $res = $this->neworderlist(1,$start,$end);
        }
    }


    //订单
    public function neworderlist($type=0,$start='',$end='')
    {
        $api = "http://api.tbk.dingdanxia.com/tbk/order_details";

        $start_time = date('Y-m-d H:i:s',time()-3600);
        $end_time = date('Y-m-d H:i:s',time());
        if ($type==1){
            $start_time = $start;
            $end_time = $end;
        }
        $data = [
            'apikey'=>$this->apikey,
            'page'=>1,
            'pageSize'=>100,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'order_scene'=>2
        ];

        $res = Http::sendRequest($api,$data);

        $result = json_decode($res['msg'],true);
        //dump($result);die;
        if ($result['code']==200){
            $list =  $result['data'];

            if ($list){
                foreach ($list as $k=>$v){
                    if (isset($v['relation_id'])){
                        $tb_sid = TbSid::where(['relation_id'=>$v['relation_id']])->where('sid_key', 'like', '%' . $v['adzone_id'].'_'.$v['relation_id'] . '%')->find();

                        $user_id = $tb_sid['user_id'];
                        $user = User::get($user_id);
                        if ($user){
                            $promotion_amount = $v['pub_share_pre_fee'];
                            //$promotion_amount = $v['total_commission_fee'];
                            //$promotion_amount = $v['total_commission_rate']*$v['item_price']/100;
                            $commission = $promotion_amount*0.56;
                            //增加消费记录
                            $consume_log_info = UserConsumeLog::get([ 'user_id'=>$user_id, 'order_no'=>$v['trade_id']]);
                            //dump($consume_log_info->consume_id);

                            if (!$consume_log_info&&array_key_exists('tk_paid_time',$v)){
                                $consume_log_model = new UserConsumeLog();
                                $consume_log_data = [
                                    'user_id'=>$user_id,
                                    'title'=>$v['item_title'],
                                    'shop_id'=>'',
                                    'shop_name'=>$v['seller_shop_title'],
                                    'image'=>$v['item_img'],
                                    'order_no'=>$v['trade_id'],
                                    'pay_time'=>strtotime($v['tk_paid_time']),
                                    'pay_price'=>$v['alipay_total_price'],
                                    'consume_type'=>2,
                                    'cps_type'=>7,
                                    'goods_id'=>$v['item_id'],
                                    'commission'=>$commission,
                                    'total_commission'=>$promotion_amount,
                                    'order_status_name'=>'已付款'
                                ];
                                User::update(['is_buy'=>1],['id'=>$user_id]);
                                $user_model = new User();
                                $user_model->upgrade($user_id);
                                $consume_log_model->save($consume_log_data);
                                UserConsumeLog::lockMemberConsumeCalculate($user_id,$consume_log_model->total_commission,$consume_log_model->consume_id,0);
                                UserConsumeLog::newrecommendShopConsumeCalculate($user_id,0,$consume_log_model->total_commission,$consume_log_model->consume_id,2);
                            } else {
                                //dump($v['tk_status']==13&&$consume_log_info->is_refund==0);
                                if ($consume_log_info){
                                    if ($v['tk_status']==3&&$consume_log_info->is_to_account==0){
                                        //发放消费记录的收益
                                        UserConsumeLog::sendCommission($consume_log_info->order_no);
                                    } elseif($v['tk_status']==13&&$consume_log_info->is_refund==0) {
                                        $consume_log_info->commission = 0;
                                        $consume_log_info->order_status_name = '退款成功';
                                        $consume_log_info->is_refund = 1;
                                        $consume_log_info->save();
                                        ExtendConsume::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                                        ExtendConsumeShop::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                                    }
                                }

                            }
                        }
                    }

                }
            }

            return $list;
        } else {
            throw new \Exception($result['msg']);
        }
    }


    public function callback($code)
    {
        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $req = new \TopAuthTokenCreateRequest;
        $req->setCode($code);
        //$req->setUuid("abc");
        $resp = $c->execute($req);

        return $resp;
    }


}